const util = require('../util')
const api = require('../api')
const config = require('../config')
const timer = require('../timer')

const logger = util.logger

const run = async (jobGroup, jobId) => {
  logger.debug('开始执行任务：', jobGroup)
  let result = await util.callLivy(api.postBatch, jobGroup.args)
  logger.debug('response batch ; ', result )
  let batchId = result.id
  return new Promise((suc,fail) => {
    let taskName = `${jobId}#${jobGroup.id}-${jobGroup.title}`
    timer.addTask({
      name: taskName,
      cycle: 30000,
      fun: async () => {
        try{
          let info = await util.callLivy(api.getBatch, undefined, batchId)
          logger.debug(`${jobId}#${jobGroup.id} info : `, info)
          if (info.state === 'success' || info.state === 'dead') {
            timer.removeTask(taskName)  //取消定时查询任务
            let log = await util.callLivy(api.getBatchLog, undefined, batchId)
            logger.debug(`${jobId}#${jobGroup.id} log : `, log)
            //获取yarn log
            if (info.appId) {
              try{
                let logFile = `${config.upload.publishDir}/log/yarn-${jobId}-${jobGroup.id}.log`
                let commond = `yarn logs -applicationId ${info.appId} > ${logFile}`
                let out = await util.runExec(commond)
                if (info.state === 'dead') {
                  fail({info, livy: log, yarn: `${config.upload.urlPrefix}/log/yarn-${jobId}-${jobGroup.id}.log`})    //成功回调
                }else{
                  suc({info, livy: log, yarn: `${config.upload.urlPrefix}/log/yarn-${jobId}-${jobGroup.id}.log`})    //成功回调
                }
              } catch (e) {
                logger.warn('导出 yarn 日志异常：', e)
                fail({info, livy: log, yarn: e.stack})    //成功回调
              }
            } else {
              fail({info, livy: log, yarn: 'applicationId is null'})    //成功回调
            }
          }
        }catch(e){
          fail(e)   //失败回调
        }
      }
    })
  })
}

//删除任务
const remove = (jobGroup, jobId) => {
  let taskName = `${jobId}#${jobGroup.id}-${jobGroup.title}`
  logger.info('删除子任务定时器：' + taskName)
  timer.removeTask(taskName)
}

// 向livy提交 spark 任务，并定时查询运行状态与日志
module.exports = {
  run, remove
}